<?php
/**
 *（Logic）解析文件（通用）
 */
namespace App\Logic\Amazon\Parse;

use App\Models\Amazon\ReportLoad;
use App\Models\Basics\AmazonAccount;
use App\Models\Basics\AmazonCountry;
use App\Models\Basics\SysPlatAccount;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
class ParseReport
{
    /**
     * 解析 AMAZON API下载的报表文件
     */
    public static function parse(){
        $parseReports = ReportLoad::query()->where('status',1)->get();//获取需要解析的数据
        $i = 0;
        $num = 50;
        while(true){
            if($parseReports->isEmpty())break;
            $_parseReport = $parseReports->splice($i,$num);
            try{
                DB::connection('mysql_amazon')->beginTransaction();

                foreach ($_parseReport as $parseReport){

                    //报告解析状态（1:未解析，2：已解析，3：解析出错，4：文件丢失）
                    $status = self::_parseReports($parseReport);
                    if(!$status == 2){
                        DB::connection('mysql_amazon')->rollBack();
                    }

                    //回写解析状态
                    $parseReport->status = $status;
                    if($status == 3) $parseReport->tries += 1;
                    $parseReport->save();
                    DB::connection('mysql_amazon')->commit();
                }

                sleep(10);
            }catch (\Exception $e){
                DB::connection('mysql_amazon')->rollBack();
                report($e);
            }
        }
    }

    /**
     * 解析报告
     * @param $parseReport
     * @return bool|int
     */
    private static function _parseReports($parseReport){

        //验证解析文件路径
        $file = self::_getParseFilePath($parseReport->account_id,$parseReport->report_id);
        if(!is_file($file))return 4;
        $account = SysPlatAccount::query()->find($parseReport->account_id);


        if(array_key_exists($parseReport->type_id,self::$_classWithAccount)){
            //退货报告、移库明细报告
            $status = (self::$_classWithAccount[$parseReport->type_id])::exeParse($file,$account);

        }elseif(array_key_exists($parseReport->type_id,self::$_classWithAccountAndId)){
            //转款报告
            $status = (self::$_classWithAccountAndId[$parseReport->type_id])::exeParse($file,$account,$parseReport->id);

        }elseif(array_key_exists($parseReport->type_id,self::$_classWithDefault)){
            //已收货库存报告
            $status = (self::$_classWithDefault[$parseReport->type_id])::exeParse($file);

        }elseif(array_key_exists($parseReport->type_id,self::$_classWithAccountAndCountry)){
            //库存报告
            $countryId = AmazonCountry::getCountryIdByMarketplaceId($parseReport->marketplace_id);
            $status = (self::$_classWithAccountAndCountry[$parseReport->type_id])::exeParse($file,$account,$countryId);

        }else{
            $status = (self::$_classWithOther[$parseReport->type_id])::exeParse($file,$account);
        }

        return $status;
    }

    /**
     * 获取文件路径
     * @param $accountId
     * @param $reportId
     * @return string
     */
    private static function _getParseFilePath($accountId,$reportId){
        $fileDir = 'app'.DIRECTORY_SEPARATOR.'amazon'.DIRECTORY_SEPARATOR.$accountId;
        $fileName = $reportId.'.txt';
        return storage_path($fileDir).DIRECTORY_SEPARATOR.$fileName;
    }

    /**
     * 已收货库存报告
     * @var string[]
     */
    private static $_classWithDefault = [
        1 => ParseFulfillmentReport::class,
    ];

    /**
     * 库存报告
     * @var string[]
     */
    private static $_classWithAccountAndCountry = [
        3 => ParseMYIInventoryReport::class,
    ];

    /**
     * ParseCustomerReturnReport(退货报告)
     * ParseRemovalShipmentReport(移库订单运输报告)(旧)(已弃用)
     * ParseInventoryReport(FBA库存报告)(旧)(已弃用)
     * ParseRemovalOrderDetailReport(移库明细报告)(新)
     * @var string[]
     */
    private static $_classWithAccount = [
        4 => ParseCustomerReturnReport::class,
       // 5 => ParseRemovalShipmentReport::class,
       // 9 => ParseInventoryReport::class,
        11 => ParseRemovalOrderDetailReport::class,
    ];

    /**
     * 转款报告
     * @var string[]
     */
    private static $_classWithAccountAndId = [
        12 => ParseDepositReport::class,
    ];

    /**
     * 转款报告2（弃用）
     * elseif(array_key_exists($parseReport->type_id,self::$_classWithAccountAndIdAndCountry)){
     *     $countryId = AmazonCountry::getCountryIdByMarketplaceId($parseReport->marketplace_id);
     *     $status = (self::$_classWithAccountAndIdAndCountry[$parseReport->type_id])::exeParse($file,$account,$countryId,$parseReport->id);
     * }
     * //private static $_classWithAccountAndIdAndCountry = [
     * //    // 12 => ParseDeposit2Report::class,
     * //];
     */

    private static $_classWithOther = [];

    public static function getReplaceStr($str){
        return str_replace(["\n","\r","\r\n"], '', $str);
    }

    public static function getTableHeadKey($str,$keys){
        if(!$str)return [];
        $temp = array_flip(explode("\t",$str));
        return Arr::only($temp,$keys);
    }
}
